from django.db.models import Q
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU
from meiduo_admin.serializers.skus import SKUImageSerializer, SKUSimpleSerializer, SKUSerializer
from rest_framework.response import Response


class SKUImageViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]
    # 指定视图所用的查询集
    queryset = SKUImage.objects.all()
    # 指定视图序列化器类
    serializer_class = SKUImageSerializer
    # GET  /meiduo_admin/skus/images/?page=<页码>&page_size=<页容量>   -->list

    # 指定路由Router生成url配置项时，从路径中提取参数的正则表达式
    lookup_value_regex = '\d+'
    # GET /meiduo_admin/skus/simple/ ---> list
    # POST /meiduo_admin/skus/simple/ ---> create

    # def create(self,request):
    #     """新增一条数据的通用代码流程"""
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()  # 调用序列化器类中的create方法
    #     return Response(serializer.data, status=201)


class SKUSimpleView(ListAPIView):
    permission_classes = [IsAdminUser]

    queryset = SKU.objects.all()
    serializer_class = SKUSimpleSerializer

    pagination_class = None


class SKUViewSet(ModelViewSet):
    permission_classes = [IsAdminUser]

    lookup_value_regex = '\d+'
    # 指定视图序列化器类
    serializer_class = SKUSerializer

    def get_queryset(self):
        """重写父类的get_queryset"""
        # 1.取keyword关键字
        keyword = self.request.query_params.get('keyword')
        # 2.
        if not keyword:
            # 查所有SKU数据
            skus = SKU.objects.all()
        else:
            # 查商品name 或caption(包含,查询条件)含有所有keyword的sku数据
            skus = SKU.objects.filter(Q(name__contains=keyword) | Q(caption__contains=keyword))

        return skus

    # GET /meiduo_admin/skus/ ->list
    # POST /meiduo_admin/skus/ ->create

    # def list(self, request):
    #     """获取一组数据的通用代码流程"""
    #     queryset = self.get_queryset()
    #     serializer = self.get_serializer(queryset, many=True)
    #     return Response(serializer.data)
